package com.ruoyi.common.core.domain

import com.ruoyi.common.constant.HttpStatus
import java.io.Serializable

/**
 * 响应信息主体
 *
 * @author ruoyi
 */
class R<T> : Serializable {
    var code = 0
    var msg: String? = null
    var data: T? = null
        private set

    fun setData(data: T) {
        this.data = data
    }

    companion object {
        private const val serialVersionUID = 1L

        /** 成功  */
        const val SUCCESS = HttpStatus.SUCCESS

        /** 失败  */
        const val FAIL = HttpStatus.ERROR
        fun <T> ok(): R<T?> {
            return restResult(null, SUCCESS, "操作成功")
        }

        fun <T> ok(data: T): R<T> {
            return restResult(data, SUCCESS, "操作成功")
        }

        fun <T> ok(data: T, msg: String): R<T> {
            return restResult(data, SUCCESS, msg)
        }

        fun <T> fail(): R<T?> {
            return restResult(null, FAIL, "操作失败")
        }

        fun <T> fail(msg: String): R<T?> {
            return restResult(null, FAIL, msg)
        }

        fun <T> fail(data: T): R<T> {
            return restResult(data, FAIL, "操作失败")
        }

        fun <T> fail(data: T, msg: String): R<T> {
            return restResult(data, FAIL, msg)
        }

        fun <T> fail(code: Int, msg: String): R<T?> {
            return restResult(null, code, msg)
        }

        private fun <T> restResult(data: T, code: Int, msg: String): R<T> {
            val apiResult = R<T>()
            apiResult.code = code
            apiResult.setData(data)
            apiResult.msg = msg
            return apiResult
        }

        fun <T> isError(ret: R<T>): Boolean {
            return !isSuccess(ret)
        }

        fun <T> isSuccess(ret: R<T>): Boolean {
            return SUCCESS == ret.code
        }
    }
}
